<template>
	<view class="android-container">
		<!-- 邻里管家信息表单 -->
		<view class="form-card">
			<view class="form-title">
				<text>邻里管家信息</text>
			</view>

			<!-- 头像上传 -->
			<view class="form-item">
				<view class="form-label">服务证件照上传</view>
				<!-- 修改点：外层容器用于布局，内部 .upload-preview 负责展示 -->
				<view class="upload-area">
					<uni-file-picker
						ref="avatarPicker"
						file-mediatype="image"
						:limit="1"
						:auto-upload="true"
						@success="handleAvatarUpload"
						@fail="handleUploadFail"
						@delete="(res) => handleAvatarDelete(res)"
						dir="/linlierAvatar"
						:image-styles="avatarStyles"
					>
						<!-- 修改点：通过给 .upload-preview 设置固定宽度和 margin: auto 来实现居中 -->
						<view class="upload-preview avatar-preview">
							<image v-if="data.avatar.url" :src="data.avatar.url" mode="aspectFill" class="upload-image"></image>
							<view v-else class="upload-placeholder">
								<!-- 修改点：使用相对路径 -->
								<image src="../../static/linlier/idCardPhoto.png" mode="aspectFit" class="placeholder-img"></image>
								<text class="upload-hint">点击上传相片</text>
							</view>
						</view>
					</uni-file-picker>
				</view>
			</view>

			<!-- 基本信息 -->
			<view class="form-item">
				<view class="form-label">真实姓名</view>
				<input class="form-input" type="text" v-model="data.realName" maxlength="4" @blur="handleblus" placeholder="请输入真实姓名" />
			</view>

			<view class="form-item">
				<view class="form-label">
					<text>服务手机号码</text>
					<text class="myphone" @click="userTelphone(storeData.user.userTel)">使用注册手机号?:{{ storeData.user.userTel }}</text>
				</view>
				<input class="form-input" v-model="data.phone" type="tel" maxlength="11" @blur="handleblus" placeholder="请输入手机号码" />
			</view>

			<!-- 身份证上传 -->
			<view class="form-item">
				<view class="form-label">身份证上传</view>
				<!-- 修改点：外层容器用于布局 -->
				<view class="upload-area">
					<view class="upload-group">
						<!-- 身份证正面 -->
						<uni-file-picker
							ref="idCardFrontPicker"
							file-mediatype="image"
							:limit="1"
							:auto-upload="true"
							@success="(res) => handleIdCardUpload(res, 'front')"
							@fail="handleUploadFail"
							@delete="(res) => handleIdCardDelete(res, 'front')"
							dir="/linlierIdCard"
							:image-styles="idCardStyles"
						>
							<!-- 修改点：通过给 .upload-preview 设置固定宽度 -->
							<view class="upload-preview idcard-preview">
								<image v-if="data.idCard.front" :src="data.idCard.front.url" mode="aspectFill" class="upload-image"></image>
								<view v-else class="upload-placeholder">
									<!-- 修改点：使用相对路径 -->
									<image src="../../static/linlier/idCardFront.png" mode="aspectFit" class="placeholder-img"></image>
									<text class="upload-hint">点击上传相片</text>
								</view>
							</view>
						</uni-file-picker>

						<!-- 身份证反面 -->
						<uni-file-picker
							ref="idCardBackPicker"
							file-mediatype="image"
							:limit="1"
							:auto-upload="true"
							@success="(res) => handleIdCardUpload(res, 'back')"
							@fail="handleUploadFail"
							@delete="(res) => handleIdCardDelete(res, 'back')"
							:image-styles="idCardStyles"
						>
							<!-- 修改点：通过给 .upload-preview 设置固定宽度 -->
							<view class="upload-preview idcard-preview">
								<image v-if="data.idCard.back" :src="data.idCard.back.url" mode="aspectFill" class="upload-image"></image>
								<view v-else class="upload-placeholder">
									<!-- 修改点：使用相对路径 -->
									<image src="/static/linlier/idCardBack.png" mode="aspectFit" class="placeholder-img"></image>
									<text class="upload-hint">点击上传相片</text>
								</view>
							</view>
						</uni-file-picker>
					</view>
				</view>
				<text class="form-note">请上传清晰的身份证正反面照片</text>
			</view>

			<!-- 自我简介 -->
			<view class="form-item">
				<view class="form-label">自我简介</view>
				<textarea class="form-textarea" v-model="data.introduction" @blur="handleblus" placeholder="请输入自我简介和服务承诺（50字以内）" maxlength="50" />
			</view>
		</view>

		<!-- 底部按钮区域 -->
		<view class="fixed-footer">
			<view class="agreement-row">
				<label @click="openAgreementPopup">
					<checkbox :checked="agree" :disabled="true" />
					<text class="agreement-text">已阅读并同意《邻里管家服务协议》</text>
				</label>
			</view>
			<button class="submit-btn" @click="formSubmit" :disabled="submitting || !agree">
				{{ submitting ? '提交中...' : '提交申请' }}
			</button>
		</view>

		<!-- 协议弹窗 -->
		<uni-popup ref="popupAgreement" type="center" :mask="true" :mask-click="false">
			<view class="agreement-popup">
				<view class="popup-title">邻里管家服务协议</view>
				<view class="agreement-scroll">
					<rich-text v-if="agreementNodes.length > 0" class="agreement-rich-text" :nodes="agreementNodes"></rich-text>
				</view>
				<view class="popup-footer">
					<button class="cancel-btn" @click="closeAgreement">取消</button>
					<button class="agree-btn" @click="confirmAgreement">同意协议</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
// [你的 script 代码保持不变]
const db = uniCloud.database();
const linlier = uniCloud.importObject('linlier', { customUI: true });
const linli = uniCloud.importObject('linliChat', { customUI: true });

export default {
	data() {
		return {
			agree: false, // 是否同意协议
			submitting: false, // 提交状态
			agreementNodes: '', // 协议富文本内容
			data: {
				realName: '',
				phone: '',
				idCard: { front: '', back: '' }, // 身份证正反面
				avatar: { url: '' }, // 头像
				userId: '',
				introduction: ''
			},
			idCardStyles: {
				width: 100,
				height: 64,

				border: {
					color: '#dddddd',
					width: 2,
					style: 'dashed',
					radius: '5px'
				}
			},

			avatarStyles: {
				width: 150,
				height: 200,
				border: {
					color: '#dddddd',
					width: 2,
					style: 'dashed',
					radius: '10px'
				}
			}
		};
	},
	computed: {
		storeData() {
			return this.$store.state.msg || {};
		}
	},
	mounted() {
		uni.$on('AppHide', (res) => {
			const fileIds = [];
			if (this.data.avatar.fileID) {
				fileIds.push(this.data.avatar.fileID);
			}
			if (this.data.idCard.back.fileID) {
				fileIds.push(this.data.idCard.back.fileID);
			}
			if (this.data.idCard.front.fileID) {
				fileIds.push(this.data.idCard.front.fileID);
			}
			this.deletePhoto(fileIds);
		});
	},
	onUnload() {
		if (!this.submitting) {
			const fileIds = [];

			if (this.data.avatar?.fileID) fileIds.push(this.data.avatar.fileID);
			if (this.data.idCard.front?.fileID) fileIds.push(this.data.idCard.front.fileID);
			if (this.data.idCard.back?.fileID) fileIds.push(this.data.idCard.back.fileID);

			if (fileIds.length > 0) {
				this.deletePhoto(fileIds).catch((err) => console.error('页面卸载时删除文件失败:', err));
			}
		}
	},
	onLoad() {
		this.loadAgreementNodes();
		this.data.userId = this.storeData.user?.userId || '';
	},

	methods: {
		// 加载协议内容
		async loadAgreementNodes() {
			try {
				const res = await db.collection('txt').where({ name: 'linlier_agreementNodes' }).get();
				if (res.result.data.length > 0) {
					this.agreementNodes = res.result.data[0].content;
				}
			} catch (e) {
				console.error('加载协议失败:', e);
			}
		},
		userTelphone(phone) {
			this.data.phone = phone;
		},
		// 打开协议弹窗
		openAgreementPopup() {
			this.$nextTick(() => {
				if (this.$refs.popupAgreement) {
					this.$refs.popupAgreement.open();
				}
			});
		},

		// 关闭协议弹窗
		closeAgreement() {
			this.$refs.popupAgreement.close();
		},

		// 确认同意协议
		confirmAgreement() {
			this.agree = true;
			this.closeAgreement();
			uni.showToast({ title: '已同意协议', icon: 'success' });
		},

		// 输入框失焦处理
		handleblus() {
			uni.hideKeyboard();
		},

		// 头像上传成功
		handleAvatarUpload(res) {
			if (res.tempFiles && res.tempFiles.length > 0) {
				this.data.avatar.url = res.tempFiles[0].url;
				this.data.avatar.fileID=res.tempFile[0].fileID
			}
		},

		// 头像删除
		handleAvatarDelete(res) {
			this.data.avatar.url = '';
			this.deletePhoto(res);
		},

		// 身份证上传成功
		handleIdCardUpload(res, type) {
			console.log(res);
			if (res.tempFiles && res.tempFiles.length > 0) {
				this.data.idCard[type] = { url: res.tempFiles[0].url, fileID: res.tempFiles[0].fileID };
			}
		},

		// 身份证删除
		async handleIdCardDelete(res, type) {
			this.data.idCard[type] = '';
			this.deletePhoto(res);
		},
		async deletePhoto(res) {
			try {
				const fileID = res.tempFile.fileID;
				const a = await linli.deleFile([fileID]);
				console.log('删除', a);
			} catch (e) {
				console.log(e);
			}
		},
		// 上传失败
		handleUploadFail(err) {
			uni.showToast({ title: `上传失败：${err.errMsg}`, icon: 'none' });
		},

		// 表单验证
		validateForm() {
			const validations = [
				{ condition: !!this.data.realName.trim(), message: '请填写真实姓名' },
				{ condition: !!this.data.phone.trim() && /^1[3-9]\d{9}$/.test(this.data.phone), message: '请输入有效手机号码' },
				{ condition: !!this.data.avatar.url, message: '请上传头像' },
				{ condition: !!this.data.idCard.front && !!this.data.idCard.back, message: '请上传身份证正反面' },
				{ condition: !!this.data.introduction.trim(), message: '请填写自我简介' },
				{ condition: this.data.introduction.trim().length <= 50, message: '自我简介不能超过50字' }
			];

			for (const item of validations) {
				if (!item.condition) {
					uni.showToast({ title: item.message, icon: 'none', duration: 2000 });
					return false;
				}
			}
			return true;
		},

		// 表单提交
		async formSubmit() {
			if (this.submitting) return;
			if (!this.agree) {
				uni.showModal({ title: '提示', content: '请阅读并同意《邻里管家服务协议》', showCancel: false });
				return;
			}
			if (!this.validateForm()) return;

			try {
				this.submitting = true;
				uni.showLoading({ title: '提交申请中...', mask: true });

				const submitData = {
					...this.data,
					location: this.storeData.location || {},
					userId: this.storeData.user?.userId || ''
				};

				const addRes = await linlier.register(submitData);
				if (addRes.code !== 0) {
					uni.showToast({
						title: '提交失败:' + addRes.message,
						position: 'center',
						duration: 2000
					});
					return;
				}

				uni.hideLoading();
				uni.showModal({
					title: '申请提交成功',
					content: '我们将在1个工作日内审核，请注意接听电话通知',
					showCancel: false,
					success: () => uni.navigateBack({ delta: 1 })
				});
			} catch (error) {
				console.error('申请提交失败:', error);
				uni.hideLoading();
				uni.showToast({ title: `提交失败：${error.message}`, icon: 'none', duration: 3000 });
			} finally {
				this.submitting = false;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
/* 全局变量 */
$primary-color: #007aff;
$text-color: #333333;
$light-text: #666666;
$border-color: #e5e5e5;
$white: #ffffff;
$gray-bg: #f4f4f4;

/* 整体容器 */
.android-container {
	padding: 20px;
	background-color: $gray-bg;
	min-height: 100vh;
	box-sizing: border-box;
}

/* 表单卡片 */
.form-card {
	background-color: $white;
	border-radius: 24rpx;
	padding: 36rpx;
	margin-bottom: 32rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.05);
}

/* 表单标题 */
.form-title {
	font-size: 32rpx;
	font-weight: 600;
	color: $text-color;
	margin-bottom: 32rpx;
	padding-left: 20rpx;
	border-left: 8rpx solid $primary-color;
}

/* 表单项目 */
.form-item {
	margin-bottom: 36rpx;
}

/* 表单标签 */
.form-label {
	font-size: 26rpx;
	color: $text-color;
	font-weight: 500;
	margin-bottom: 16rpx;
	display: block;
	gap: 50rpx;
	.myphone {
		margin-left: 50rpx;
		color: #007aff;
	}
}

/* 输入框样式 */
.form-input {
	width: 100%;
	height: 72rpx;
	border: 2rpx solid $border-color;
	border-radius: 16rpx;
	padding: 0 24rpx;
	font-size: 26rpx;
	color: $text-color;
	box-sizing: border-box;
	transition: border-color 0.3s;

	&:focus {
		border-color: $primary-color;
		outline: none;
	}
}

/* 文本域样式 */
.form-textarea {
	width: 100%;
	min-height: 140rpx;
	border: 2rpx solid $border-color;
	border-radius: 16rpx;
	padding: 24rpx;
	font-size: 26rpx;
	color: $text-color;
	resize: vertical;
	box-sizing: border-box;
	transition: border-color 0.3s;

	&:focus {
		border-color: $primary-color;
		outline: none;
	}
}

/* --- 以下是主要修改的样式 --- */

/* 上传区域外层容器，负责控制整体布局 */
.upload-area {
	width: 100%;
	// 可以在这里添加一些margin等样式
}

/* 单个上传预览容器 */
.upload-preview {
	border-radius: 16rpx;
	overflow: hidden;
	position: relative;
	border: 2rpx dashed #ddd; /* 给未上传时也加上边框，更美观 */
}

/* 服务证件照上传预览 (居中) */
.avatar-preview {
	width: 300rpx; /* 设置一个固定宽度 */
	height: 200rpx;
	margin: 0 auto; /* 关键：水平居中 */
}

/* 身份证上传预览 (并排) */
.upload-group {
	display: flex;
	justify-content: center; /* 让两个身份证框整体居中 */
	gap: 20rpx;
}
.idcard-preview {
	width: 160rpx; /* 设置一个固定宽度 */
	height: 100rpx;
}

/* 上传图片样式 */
.upload-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

/* 未上传占位图 */
.upload-placeholder {
	width: 100%;
	height: 100%;
	background-color: $gray-bg;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

/* 占位图中的图片样式 */
.placeholder-img {
	width: 50rpx; /* 缩小图标 */
	height: 50rpx;
	margin-bottom: 10rpx; /* 与文字保持距离 */
}

/* --- 修改结束 --- */

/* 上传提示文字 */
.upload-hint {
	font-size: 22rpx;
	color: #999;
}

/* 表单备注 */
.form-note {
	font-size: 22rpx;
	color: #999;
	margin-top: 12rpx;
	display: block;
}

/* 底部按钮区域 */
.fixed-footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: $white;
	padding: 32rpx 36rpx;
	box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.05);
	box-sizing: border-box;
}

/* 协议行 */
.agreement-row {
	margin-bottom: 24rpx;
	font-size: 26rpx;
	display: flex;
	align-items: center;

	gap: 16rpx;
}

.agreement-text {
	color: #666;
	text-decoration: underline;
	color: $primary-color;
}

/* 提交按钮 */
.submit-btn {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 96rpx;
	background-color: $primary-color;
	color: $white;
	font-size: 32rpx;
	font-weight: 500;
	border-radius: 48rpx;
	border: none;
	transition: opacity 0.3s, background-color 0.3s;

	&:disabled {
		background-color: #ccc;
		opacity: 0.8;
	}

	&:not(:disabled):active {
		background-color: #0066cc;
	}
}

/* 协议弹窗 */
.uni-popup--center {
	z-index: 9999 !important;
}

.agreement-popup {
	width: 90%;
	max-width: 600rpx;
	max-height: none;
	background-color: $white;
	border-radius: 24rpx;
	padding: 32rpx;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	// max-height: 80vh;
}

.popup-title {
	font-size: 32rpx;
	font-weight: 600;
	color: $text-color;
	text-align: center;
	margin-bottom: 20rpx;
	padding-bottom: 16rpx;
	border-bottom: 2rpx solid $border-color;
}

.agreement-scroll {
	flex: 1;
	overflow-y: auto;
	margin-bottom: 24rpx;
	line-height: 1.8;
	font-size: 26rpx;
	color: $text-color;
	height: auto;
}

.popup-footer {
	display: flex;
	gap: 20rpx;
	margin-top: 16rpx;
}

.cancel-btn,
.agree-btn {
	flex: 1;
	height: 76rpx;
	border-radius: 16rpx;
	font-size: 28rpx;
	font-weight: 500;
}

.cancel-btn {
	background-color: $gray-bg;
	color: $light-text;
}

.agree-btn {
	background-color: $primary-color;
	color: $white;
}
.agreement-rich-text {
	// 重置父节点样式，避免影响子节点
	font-size: inherit;
	color: inherit;
	line-height: inherit;

	// 确保text节点的样式生效
	> div,
	> h1,
	> strong {
		all: unset; // 清除父节点的默认样式
	}

	// 重新应用必要的样式
	h1 {
		text-align: center;
		margin: 32rpx 0;
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	div {
		margin-bottom: 32rpx;
	}
	strong {
		display: block;
		margin: 16rpx 0;
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}
	text {
		display: block;
		margin: 8rpx 0;
		font-size: 28rpx;
		color: #666;
		line-height: 1.8;
	}
}
</style>
